package org.quipu.client;

import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import java.util.ArrayList;
import java.util.List;
import org.quipu.client.events.AppEvent;
import org.quipu.client.events.AppEventBus;

public class Form extends AppEventWidget {

    private final VerticalPanel vPanel;
    private final List<HorizontalPanel> rows;

    public Form(AppEventBus eventBus, AppCache cache) {
        super(eventBus, cache);
        vPanel = new VerticalPanel();
        rows = new ArrayList<HorizontalPanel>();
    }

    public Form addRow() {
        HorizontalPanel hPanel = new HorizontalPanel();
        rows.add(hPanel);
        vPanel.add(hPanel);
        return this;
    }

    public void clearRow(int row) {
        if(row < 0 || row >= rows.size()) {
            throw new IndexOutOfBoundsException("No row with such index in form");
        }
        HorizontalPanel hPanel = rows.get(row);
        hPanel.clear();
    }

    public Form addCell(Widget w) {
        HorizontalPanel hPanel = rows.get(rows.size() - 1);
        hPanel.add(w);
        return this;
    }

    public Form addCell(String label) {
        return addCell(new Label(label));
    }

    public Form addCell(int row, Widget w) {
        if(row < 0 || row >= rows.size()) {
            throw new IndexOutOfBoundsException("No row with such index in form");
        }
        HorizontalPanel hPanel = rows.get(row);
        hPanel.add(w);
        return this;
    }

    public Form addCell(int row, String label) {
        return addCell(row, new Label(label));
    }

    @Override
    public void init() {
    }

    @Override
    public Widget getWidget() {
        return vPanel;
    }

    @Override
    public void handleEvent(AppEvent event) {
    }
}
